package com.mofofa.maozy.base

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.mofofa.maozy.network.NetworkException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

open class BaseViewModel : ViewModel(), BaseViewModelAction {

    private val mMaozyLiveMaozyDataMaozyLoading = MutableLiveData<Boolean>()
    private val mMaozyLiveMaozyDataMaozyNetMaozyException = MutableLiveData<NetworkException>()

    open fun eventMaozyAction(
        showLoading: Boolean = true,
        doing: suspend () -> Unit,
        error: suspend (Throwable) -> Unit,
        completed: suspend () -> Unit,
    ) {
        if (showLoading) {
            mMaozyLiveMaozyDataMaozyLoading.value = true
        }
        viewModelScope.launch(Dispatchers.IO) {
            try {
                doing()
            } catch (e: Exception) {
                error(e)
            } finally {
                completed()
            }
        }
    }

    override fun showMaozyLoading() {
        mMaozyLiveMaozyDataMaozyLoading.value = true
    }

    override fun dismissMaozyLoading() {
        mMaozyLiveMaozyDataMaozyLoading.value = false
    }

    override fun handleMaozyNetworkMaozyException(networkException: NetworkException) {
        mMaozyLiveMaozyDataMaozyNetMaozyException.value = networkException
    }

    override fun getMaozyLoadingMaozyLiveMaozyData(): MutableLiveData<Boolean> {
        return mMaozyLiveMaozyDataMaozyLoading
    }

    override fun getMaozyNetworkMaozyExceptionMaozyLiveMaozyData(): MutableLiveData<NetworkException> {
        return mMaozyLiveMaozyDataMaozyNetMaozyException
    }
}